const util = require('../../utils/util.js');
//获取应用实例
const app = getApp();
const {
  $Toast
} = require('../../dist/base/index');
Page({
  data: {
    active: 0,
    userInfo: {},
    hiddenmodalput: true,
    hiddenName: true,
    canIUse: wx.canIUse('button.open-type.getUserInfo'), 
    canvasWidth: "",
    canvasHeight: "",
    canvasLeft: "",
    canvasTop: "",
    maskHidden: true, //隐藏显示
    registInfo: {},
    code_disanled: false,
    currenttime: '获取验证码',
    unreadCount: 0
  },

  aboutUs: function() {
    wx.navigateTo({
      url: '/pages/details/details?id=21893',
    });
  },

  onLoad: function() {
    var that = this;

    this.setData({
			checkStatus: wx.getStorageSync("checkStatus"),
      unreadCount: wx.getStorageSync("unreadCount"),
      unreadMessage: wx.getStorageSync("unreadMessage")
    });

    //获取用户的当前设置。返回值中只会出现小程序已经向用户请求过的权限。
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          try {
            var value = wx.getStorageSync('userInfo');
            var loginInfo = wx.getStorageSync("loginInfo");

            if (value) {
              app.globalData.userInfo = value;
              that.setData({
                userInfo: value
              });
            } else {
              $Toast({
                content: '请先登录',
                type: 'warn'
              });
              that.setData({
                hiddenName: false
              });
            }
          } catch (e) {
            console.log(e);
          }

        } else {
          that.setData({
            userInfo: app.globalData.userInfo,
            hiddenName: false
          });
          $Toast({
            content: '请先登录',
            type: 'warn'
          });
        }
      }
    });
  },

  exitLogin: function() {
    wx.clearStorage();
    wx.reLaunch({
      url: '/pages/userinfo/userinfo',
    })
  },

  message: function() {
    wx.navigateTo({
      url: '/pages/message/message',
    });
  },

  bindGetUserInfo: function(e) {
    var that = this;
    //授权按钮
    if (e.detail.userInfo) {
      //本地缓存
      wx.setStorageSync('userInfo', e.detail.userInfo);
      this.setData({
        userInfo: e.detail.userInfo,
        hasUserInfo: true
      });
      this.setData({
        hiddenName: true
      });
      //调用登录
      wx.login({
        success(res) {
          if (res.code) {
            var code = res.code;
            // 必须是在用户已经授权的情况下调用
            wx.getUserInfo({
              success(res) {
                var userInfo = res.userInfo;
                //通过code换取openid
                wx.request({
                  url: util.basePath + '/users/getOpenidInfo',
                  method: "post",
                  data: {
                    code: code
                  },
                  header: {
                    'content-type': 'application/json'
                  },
                  success(res) {
                    if (res.data.status == 200) {
                      userInfo.openid = res.data.payload;
                      //若openid未注册，则弹出绑定手机号弹框获取验证码绑定手机号
                      that.setData({
                        hiddenmodalput: !that.data.hiddenmodalput,
                        registInfo: userInfo,
                        userInfo: userInfo
                      });
                    } else {
                      wx.setStorage({
                        key: 'loginInfo',
                        data: res.data.err,
                      });
                      $Toast({
                        content: '登陆成功',
                        type: 'success'
                      });
                    }

                    that.checkStatus();
                  }
                });
              }
            });
          }
        }
      });
    } else {
      //用户不同意授权
      this.setData({
        hiddenName: false
      });
    }
  },

  checkStatus: function() {
    var that = this;

    wx.request({
      url: util.basePath + '/article/v1/checkStatus',
      method: "post",
      data: {
        v: '1.0.8'
      },
      header: {
        'content-type': 'application/json'
      },
      success(res) {
        if (res.data.status == 200) {
          that.setData({
            checkStatus: true
          });
          wx.setStorage({
            key: 'checkStatus',
            data: true
          });
        } else {
          that.setData({
            checkStatus: false
          });
          wx.setStorage({
            key: 'checkStatus',
            data: false
          });
        }
      }
    });
  },

  //获取手机号输入框的值
  accountInput: function(e) {
    this.setData({
      ['registInfo.account']: e.detail.value
    });
  },

  //获取验证码输入框的值
  codeInput: function(e) {
    this.setData({
      ['registInfo.verify_code']: e.detail.value
    });
  },
  //获取验证码
  apply_code: function(e) {
    var that = this;

    that.setData({
      currenttime: 60
    });

    if (that.data.registInfo.account.length != 11) {
      that.cancel();
      $Toast({
        content: '手机号不能为空!',
        type: 'error'
      });
    } else {
      wx.request({
        url: util.basePath + '/users/apply_code',
        method: "post",
        data: {
          account: that.data.registInfo.account,
          app_sid: 'nyl',
          type: '0'
        },
        header: {
          'content-type': 'application/json'
        },
        success(res) {
          if (res.data.status == 200) {

            var currenttime = that.data.currenttime;

            var interval = setInterval(function() {
              that.setData({
                currenttime: currenttime - 1 + '秒',
                code_disanled: true
              });

              currenttime--;

              if (currenttime <= 0) {
                clearInterval(interval);
                that.setData({
                  currenttime: '获取验证码',
                  code_disanled: false
                });
              }
            }, 1000);
          } else {
            that.cancel();
            $Toast({
              content: '获取验证码异常!',
              type: 'error'
            });
          }
        }
      });
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    return {
      title: '空城丶Blog',
      path: '/pages/userinfo/userinfo'
    }
  },
  onReady: function() {

  },
  //取消绑定手机号
  cancel: function() {
    wx.clearStorage("userinfo");
    this.setData({
      userInfo: app.globalData.userInfo
    });
    this.setData({
      hiddenName: false
    });
    this.setData({
      hiddenmodalput: !this.data.hiddenmodalput
    });
  },
  onShow: function() {
    this.setData({
      maskHidden: true,
      showhaibao: false
    });
  },
  develop: function() {
    wx.showToast({
      title: "尚待开发!",
      icon: "warn",
    });
  },
  //点击图片进行预览，长按保存分享图片
  previewImg: function(e) {
    var img = this.data.imagePath
    wx.previewImage({
      current: img, // 当前显示图片的http链接
      urls: [img] // 需要预览的图片http链接列表
    })
  },
  onPullDownRefresh() {
    // 显示顶部刷新图标
    wx.showNavigationBarLoading();
    setTimeout(function() {
      // 隐藏导航栏加载框
      wx.hideNavigationBarLoading();
      //停止当前页面下拉刷新。
      wx.stopPullDownRefresh();
    }, 1000);
  },
  confirm: function() {
    var that = this;
    var userInfo = this.data.registInfo;
    userInfo.type = '0';
    console.log(userInfo);

    wx.request({
      url: util.basePath + '/users/wx_regist',
      method: "post",
      data: userInfo,
      header: {
        'content-type': 'application/json'
      },
      success(res) {
        if (res.data.status == 200) {
          wx.setStorage({
            key: 'loginInfo',
            data: res.data.payload,
          });
          that.setData({
            hiddenmodalput: !that.data.hiddenmodalput
          });
          $Toast({
            content: '注册成功',
            type: 'success'
          });
        } else {
          that.cancel();
          $Toast({
            content: res.data.err,
            type: 'error'
          });
        }
      }
    });
  }
});